package com.woniuxy.creditsystem.systemmag.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.woniuxy.creditsystem.annos.MyLog;
import com.woniuxy.creditsystem.common.bean.ResultMsg;
import com.woniuxy.creditsystem.common.bean.UserInfo;
import com.woniuxy.creditsystem.common.mapper.UserMapper;
import com.woniuxy.creditsystem.systemmag.service.IDownloadService;
import com.woniuxy.creditsystem.systemmag.service.IUserService;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

/**
 * 用户的增、删、查、改
 * @author hejie
 */
@Transactional(readOnly = true)
@Service
public class UserServiceImpl implements IUserService {

    @Resource
    private UserMapper userMapper;
    //用来把导出的excel信息，存储到download_info表中。供“下载中心”中下载该excel文件
    @Resource
    private IDownloadService downloadServiceImpl;

    /**
     * 新增管理员
     * @author hejie
     * @param userInfo
     * @return
     */
    @MyLog(value = "新增一个用户")
    @Transactional(isolation = Isolation.REPEATABLE_READ,rollbackFor = Exception.class)
    @Override
    public int saveUserBean(UserInfo userInfo) {
        return userMapper.saveUserBean(userInfo);
    }

    /**
     * 修改用户（可以修改所有的用户。登录者必须能看到 系统管理-账号管理）
     * @author hejie
     * @param userInfo
     * @return
     */
    @MyLog(value = "修改用户")
    @Transactional(isolation = Isolation.REPEATABLE_READ,rollbackFor = Exception.class)
    @Override
    public int updateUserBean(UserInfo userInfo) {
        if (userInfo.getPassword()!=null && userInfo.getUserName()!=null){
            //加盐 加密
            String newPassword=new SimpleHash("MD5",
                    userInfo.getPassword(),
                    userInfo.getUserName().getBytes(),
                    1024).toString();
            userInfo.setPassword(newPassword);
        }
        return userMapper.updateUserBean(userInfo);
    }

    /**
     * 用户修改自己的密码
     * @author hejie
     * @param password 前端传递密码
     * @return
     */
    @MyLog(value = "用户修改自己的密码")
    @Transactional(isolation = Isolation.REPEATABLE_READ,rollbackFor = Exception.class)
    @Override
    public int updateMyPassword(String password) {
        if (password !=null){
            //从Session中获得用户
            Subject subject = SecurityUtils.getSubject();
            Session session = subject.getSession();
            UserInfo userInfo = (UserInfo) session.getAttribute("user");

            //加盐 加密
            String newPassword=new SimpleHash("MD5",
                    password,
                    userInfo.getUserName().getBytes(),
                    1024).toString();
            userInfo.setPassword(newPassword);
            return userMapper.updateUserBean(userInfo);
        }
        return 0;
    }

    /**
     * 删除用户
     * @author hejie
     * @param id
     * @return
     */
    @MyLog(value = "删除用户")
    @Transactional(isolation = Isolation.REPEATABLE_READ,rollbackFor = Exception.class)
    @Override
    public int deleteUserBean(Long id) {
        return userMapper.deleteUserBean(id);
    }

    /**
     * 获取一个UserInfo信息
     * @author hejie
     * @param id
     * @return
     */
    @Override
    public UserInfo getOneById(Long id) {
        return userMapper.getOneById(id);
    }

    /**
     * 分页查询（使用的针对MyBatis的分页插件pageHelper）
     * @author hejie
     * @param pageNum 起始页
     * @param pageSize 每页多少条
     * @param userInfo
     * @return
     */
//    @MyLog(value = "对用户表分页查询")
    @Override
    public PageInfo<UserInfo> findAllByParams(int pageNum, int pageSize, UserInfo userInfo) {
        return PageHelper.startPage(pageNum,pageSize).
                doSelectPageInfo(()->userMapper.findAllByParams(userInfo));
    }

    /**
     * 把页面传回来的table数据，写入到excel文件中
     * @param tableDataJson
     * @return
     */
    @MyLog(value = "POI，导出账号管理查询结果为excel文件")
    @Transactional(isolation = Isolation.REPEATABLE_READ, rollbackFor = Exception.class)
   public ResultMsg write2excel(List<UserInfo> tableDataJson ,String path,String simpleFileNameUserSet) throws IOException {
       if (tableDataJson==null){
           return new ResultMsg(201,"页面表格内容为空，没有数据可以导出！",null);
       }


       //创建表对象，即工作簿对象
       HSSFWorkbook workbook = new HSSFWorkbook();
       //第一个sheet对象demo1
       HSSFSheet sheet = workbook.createSheet("demo1");
       //行对象
       HSSFRow row = sheet.createRow(0);
       //单元格对象
       HSSFCell cell0 = row.createCell(0);
       cell0.setCellValue("用户名");
       HSSFCell cell1 = row.createCell(1);
       cell1.setCellValue("角色名称");
       HSSFCell cell2 = row.createCell(2);
       cell2.setCellValue("状态");
       HSSFCell cell3 = row.createCell(3);
       cell3.setCellValue("职位");
       HSSFCell cell4 = row.createCell(4);
       cell4.setCellValue("手机号");
       HSSFCell cell5 = row.createCell(5);
       cell5.setCellValue("创建时间");

       //解决日期显示不正常的问题：给第1行、第2列单元格写入日期
       //用Excel表对象获取CreationHelper对象
       CreationHelper createHelper = workbook.getCreationHelper();
       //用Excel表对象创建CellStyle对象
       CellStyle cellStyle = workbook.createCellStyle();
       //给cellStyle对象设置Date格式
       cellStyle.setDataFormat(createHelper.createDataFormat().getFormat("yyyy-MM-dd HH:mm:ss"));

       for (int i=0; i<tableDataJson.size(); i++){
            //行对象
           HSSFRow r = sheet.createRow(1+i);
           for (int j=0; j<6; j++){
               //单元格对象
               HSSFCell cellUserName = r.createCell(0);
               cellUserName.setCellValue(tableDataJson.get(i).getUserName());
               HSSFCell cellRoleDesc = r.createCell(1);
               cellRoleDesc.setCellValue(tableDataJson.get(i).getRoleInfo().getRoleDesc());
               HSSFCell cellStatus = r.createCell(2);
               String status="";
               if (tableDataJson.get(i).getStatus()==1){
                   status="已启用";
               }else {
                   status="已禁用";
               }
               cellStatus.setCellValue(status);
               HSSFCell cellJob = r.createCell(3);
               cellJob.setCellValue(tableDataJson.get(i).getJob());
               HSSFCell cellTelephone = r.createCell(4);
               cellTelephone.setCellValue(tableDataJson.get(i).getTelephone());
               HSSFCell cellCreateTime = r.createCell(5);
               //设置 “Date”类型的显示格式
               cellCreateTime.setCellStyle(cellStyle);
               cellCreateTime.setCellValue(tableDataJson.get(i).getCreateTime());
           }
       }

       FileOutputStream os = null;
       //fileName是excel文件名字：包含了“.excel”，该路径需要存到的“download_info表”的“file_path”字段
       //不含后缀名“.xls”
       String simpleFileName= "账号管理" + System.currentTimeMillis();
        //如果用户要自己设置文件名字，就要传入非空的名字
        if (simpleFileNameUserSet!=null && !("".equals(simpleFileNameUserSet))){
            simpleFileName=simpleFileNameUserSet;
        }
       String filePathName = path +File.separator + simpleFileName + ".xls";
       File file=new File(path);
       if (!file.exists()){
           file.mkdirs();
       }
       try {
           os = new FileOutputStream(filePathName);
       } catch (FileNotFoundException e) {
           e.printStackTrace();
       }
       //		workbook1.write(os);
       try {
           workbook.write(os);
       } catch (IOException e) {
           e.printStackTrace();
       }
       os.flush();
       os.close();

        //把 文件名+后缀 放到ResultMsg的data中返回，方便：“新增下载”时，能够直接自动开始下载，而不用费力去“下载中心”点击“下载”
       ResultMsg resultMsg=  new ResultMsg(200,"页面表格数据已经写入到"+filePathName,simpleFileName + ".xls");

       //把当前“下载中心”记录写入到数据库download_info
       //simpleFileName是excel名字，不含后缀名 （存储到download_info表中的excel文件名是 simpleFileName.xsl，simpleFileName是变量）
       downloadServiceImpl.saveExcelInfo2downloadInfo(simpleFileName);
        return resultMsg;

    }
}
